package com.attrisoft.sanger.wrapper;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class Clusters {
    
    public static void main(String[] argv) throws Exception {
        
        List<String> ridx = new ArrayList<String>();
        BufferedReader reader = new BufferedReader(new FileReader("out/data.ridx"));
        for (String line; (line = reader.readLine()) != null;) 
            ridx.add(line);
        reader.close();
        reader = new BufferedReader(new FileReader("out/out.data.mci"));
        int clusters = 1;
        for (String line; (line = reader.readLine()) != null;) {
            if (line.startsWith("dimensions")) {
                clusters = Integer.parseInt(line.substring(line.indexOf('x')+1));
            } else if (line.startsWith(" ")) {
                continue;
            } else if (clusters > 1) {
                try {
                    StringTokenizer st = new StringTokenizer(line, " ");
                    int cluster = Integer.parseInt(st.nextToken());
                    if (cluster > 0) {
                        String remaining = line.substring(line.indexOf(" ")).trim();
                        st = new StringTokenizer(remaining, " ");
                        PrintWriter writer = new PrintWriter(
                            new FileOutputStream("output/cluster"+cluster+".txt"));
                        while (st.hasMoreTokens()) {
                            String token = st.nextToken().trim();
                            if (!("$".equals(token))) {
                                int rid = Integer.parseInt(token);
                                writer.println(ridx.get(rid));
                            }
                        }
                        writer.close();
                    }
                } catch (Exception e) { 
                    // Ignore,
                }
            }
        }
    }
}
